<?php 
  $conn_str = 'host=dbsrv1.cdf.toronto.edu dbname=csc309g23 user=csc309g23 password=ipheid5h';
  $conn = pg_connect($conn_str);  
  if (isset($_POST['rating'])) {
	if ($_POST['revote'] == 0) {
	  
	  if ($_POST['organizer'] ==0 ) {
		$query = 'INSERT INTO rating VALUES (\'' . 
				$_POST['voter'] . '\', \'' .
				$_POST['player'] . '\',' .
				$_POST['gameid'] . ', \'' .
				$_POST['sport'] . '\', NULL, ' .
				$_POST['rating'] . ', FALSE)';	  		
	  } else {
		$query = 'INSERT INTO rating VALUES (\'' . 
		  $_POST['voter'] . '\', \'' .
		  $_POST['player'] . '\',' .
		  $_POST['gameid'] . ', \'' .
		  $_POST['sport'] . '\', ' .
		  $_POST['rating'] . ', NULL, TRUE)';		
	  }	  
	  pg_query($conn, $query);
	  // now update player overall rating
	  $updateoverall = 'UPDATE members SET playrating = (select sum(playing)/count(playing) from rating where player = \''.$_POST['player'].'\') , orgrating =(select sum(organizing)/count(organizing) from rating where player = \''.$_POST['player'].'\') WHERE username=\''.$_POST['player'].'\'';
	  pg_query($conn, $updateoverall);
	  
	} else { 
	
	  if ($_POST['organizer'] == 0 ) {
		$query = 'UPDATE rating SET playing=' . $_POST['rating'] . 
				 ' WHERE voter=\'' . $_POST['voter'] . 
				 '\' AND player=\'' . $_POST['player'] . 
				 '\' AND gameid=' . $_POST['gameid'] .
				 ' AND orgvote is FALSE';		
	  } else {
		$query = 'UPDATE rating SET organizing=' . $_POST['rating'] . 
				 ' WHERE voter=\'' . $_POST['voter'] . 
				 '\' AND player=\'' . $_POST['player'] . 
				 '\' AND gameid=' . $_POST['gameid'] .
				 ' AND orgvote is TRUE';		
	  }
	  
	  pg_query($conn, $query);
	  $updateoverall = 'UPDATE members SET playrating = (select sum(playing)/count(playing) from rating where player = \''.$_POST['player'].'\') , orgrating =(select sum(organizing)/count(organizing) from rating where player = \''.$_POST['player'].'\') WHERE username=\''.$_POST['player'].'\'';
	  pg_query($conn, $updateoverall);
	}
	
  }
  header('Location: ' . $_SERVER['HTTP_REFERER']);
?>